package org.ank.food;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class InetManager {
	private Context context;
	private volatile static InetManager instance;
	
	private static final String IMAGE_SERACH_API_URL = 
		"http://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=large&q=";
	private static final String URL_PREFIX_STRING = "unescapedUrl\":\"";
	
	private InetManager(Context c) {
		this.context = c;
	}
 
	public static InetManager getInstance(Context context) {
        if (instance == null) {
            synchronized (InetManager.class) {
                if (instance == null) {
                    instance = new InetManager(context);
                }
            }
        }
        return instance;
    }
	
	private String getImageSearchResult(String request){
		//Log.v("inet manager", "get search result - start");
		StringBuffer preparedRequest = new StringBuffer(request);
		
		for (int i = 0; i < preparedRequest.length(); i++)
			if(preparedRequest.charAt(i) == ' ')
				preparedRequest.setCharAt(i, '+');
		//Log.v("inet manager", "get search result - prepared request = "+preparedRequest);
		StringBuffer result = new StringBuffer();
		try {
            URL url = new URL(IMAGE_SERACH_API_URL+preparedRequest);
            BufferedReader reader = new BufferedReader(
            		new InputStreamReader( url.openStream() ) );
            String line;
            while ((line = reader.readLine()) != null) {
            	result.append(line);
            }
            reader.close();
        } catch (MalformedURLException e) {
        	e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        	return null;
        }
        //Log.v("inet manager", "get search result - result = "+result);
        return result.toString();
	}
	
	public ArrayList<BitmapDrawable> getProductDrawables(int prodId){
		//Log.v("inet manager", "get drawables - start");
		ArrayList<BitmapDrawable> result = new ArrayList<BitmapDrawable>();
		String name = ProductDataManager.getInstance(context).
				getProductNameById(prodId);
		//Log.v("inet manager", "get drawables - name = "+name);
		ArrayList<String> pictureURLArray = getPictureUrlAdresses(
				getImageSearchResult(name) );
		if (pictureURLArray == null)
			return null;
		int amount = pictureURLArray.size();
        for (int i = 0; i < amount; i ++){
        	try {
        		URL pictureURL = new URL(pictureURLArray.get(i));
        		//Log.v("inet manager", "picture url = "+pictureURL);
        		InputStream is = pictureURL.openStream();
        		BitmapDrawable picture = new BitmapDrawable(is);
        		//Log.v("inet manager", "drawable created");
        		result.add(picture);
        		//Log.v("inet manager", "drawable added");
        		is.close();
        	} catch (MalformedURLException e) {
        		//Log.v("inet manager", "malformed exception");
        		e.printStackTrace();
        	} catch (IOException e) {
        		//Log.v("inet manager", "IOexception");
        		e.printStackTrace();
        		continue;
        	}
        }
        //Log.v("inet manager", "now the array has "+result.size()+" items");
        return result;
	}
	
	private ArrayList<String> getPictureUrlAdresses(String serverResponce){
		if (serverResponce == null || serverResponce.length() == 0)
			return null;
		//Log.v("inet manager", "get picture URLs - start");
		ArrayList<String> adressList = new ArrayList<String>();
		int searchStart = 0, urlStart, urlEnd;
		while (  (urlStart = serverResponce.indexOf(URL_PREFIX_STRING, searchStart)) != -1  ){
			urlStart = urlStart + URL_PREFIX_STRING.length();
			urlEnd = serverResponce.indexOf("\"", urlStart);
			adressList.add(serverResponce.substring(urlStart, urlEnd));
			//Log.v("inet manager", "URL is "+serverResponce.substring(urlStart, urlEnd));
			searchStart = urlEnd;
		}
		return adressList;
	}
	

	
}
